import router from '@/router';
import { defineStore } from 'pinia';
import { Local } from '@/assets/utils/storage';
import { loginApi, logoutApi, checkApi } from '@/api/auth';
import { isNotNull } from '@/assets/utils/obj';

export const storeKey = 'token';
export const userinfoKey = 'userinfo';

export const useAuthStore = defineStore('authStore', {
  state: () => ({
    auth: Local.get(storeKey) || {
      token: '',
      statu: 'WAIT'
    },
    userinfo: Local.get(userinfoKey) || {
      userId: '',
      username: '暂未登录',
      nickname: '暂未登录',
      avatar: '',
    }
  }),
  actions: {
    loginEscape() {
      this.reset();
      router.push('/home');
    },
    loginByPassword(username: string, password: string) {
      loginApi({
        username: username,
        password: password,
        clientId: 'guardcat',
        grantType: 'password'
      }).then((resp: any) => {
        let auth = {
          token: resp.data.token,
          statu: 'SUCC'
        };
        this.auth = auth;
        Local.set(storeKey, auth);
        this.checkToken();
      }).catch(() => {

      })
    },
    logout() {
      logoutApi().then(_ => {
        this.reset();
        router.push('/login');
      })
    },
    checkToken() {
      if (isNotNull(this.auth) && isNotNull(this.auth.token)) {
        checkApi().then(resp => {
          let userinfo = {
            userId: resp.data.metadata.userId,
            username: resp.data.metadata.username,
            nickname: resp.data.metadata.nickname,
            avatar: resp.data.metadata.avatar || '@/assets/imgs/default_user_avatar.jpg',
          }
          this.userinfo = userinfo;
          Local.set(userinfoKey, userinfo)
          router.push('/home');
        }).catch(resp => {
        })
      }
    },
    reset() {
      Local.remove(storeKey);
      Local.remove(userinfoKey);
      this.auth = {
        token: '',
        statu: 'WAIT'
      }
      this.userinfo = {
        userId: '',
        username: '暂未登录',
        nickname: '暂未登录',
        avatar: '',
      }
    }
  }
});